<?php

namespace App\Http\Controllers\Admin;

use App\Models\Node;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;

class NodeController extends Controller
{
    /**
     * 节点列表展示
     */
    public function index()
    {
        $model = new Node();
        // 获取节点
        $data = $model->getAllList();
        return view('admin.node.index', compact('data'));
    }

    /**
     * 添加页面显示
     */
    public function create()
    {
        $data = (new Node())->getAllList();
        // $data = Node::get();
        return view('admin.node.create', compact('data'));
    }

    /**
     * 保存新建数据至数据库
     */
    public function store(Request $request)
    {
        try {
            $data = $this->validate($request, [
                'name'       => 'required|unique:nodes,name',
                'is_menu'    => 'required',
                'route_name' => 'nullable',
                'pid'        => 'required'
            ]);
        } catch (\Exception $e) {
            return ['msg' => '验证不通过', 'status' => 404];
        }
        Node::create($data);
        return ['msg' => '添加节点成功', 'status' => 200];
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Node $node
     * @return \Illuminate\Http\Response
     */
    public function show(Node $node)
    {
        //
    }

    /**
     * 节点修改页面展示
     */
    public function edit(Node $node)
    {
        // 获取所有节点
        $data = (new Node)->getAllList();
        return view('admin.node.edit', compact('node', 'data'));
    }

    /**
     * @param Request $request
     * @param Node $node
     * @return array
     */
    public function update(Request $request, int $id)
    {
        try {
            $data = $this->validate($request, [
                'name'       => 'required',
                'is_menu'    => 'required',
                'pid'        => 'required'
            ]);
        } catch (\Exception $e) {
            return ['msg' => $e->getMessage(), 'status' => 404];
        }
        Node::where('id', $id)->update($data);
        return ['msg' => '修改成功', 'status' => 200];
    }

    /**
     * 删除节点node
     */
    public function destroy(Node $node)
    {
        Node::destroy($node->id);
        return ['msg' => '删除成功', 'status' => 200];
    }
}
